package com.vogue.supplymall.match.controller;

import com.google.gson.Gson;
import com.vogue.supplymall.account.domain.service.BaseCodeService;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.domain.validate.Regex;
import com.vogue.supplymall.match.domain.dto.BaseDTO;
import com.vogue.supplymall.match.domain.dto.OrderDetailPullResultDTO;
import com.vogue.supplymall.match.domain.dto.OrderPayVoucherDTO;
import com.vogue.supplymall.match.domain.dto.OrderPullCountDTO;
import com.vogue.supplymall.match.domain.dto.OrderPullDTO;
import com.vogue.supplymall.match.domain.dto.OrderPullResultDTO;
import com.vogue.supplymall.match.domain.dto.OrderPushDTO;
import com.vogue.supplymall.match.domain.dto.PushBillInfoDTO;
import com.vogue.supplymall.match.domain.dto.RefundDetailPullResultDTO;
import com.vogue.supplymall.match.domain.dto.RefundPullResultDTO;
import com.vogue.supplymall.match.domain.dto.UploadDTO;
import com.vogue.supplymall.match.domain.service.ColValidateService;
import com.vogue.supplymall.match.domain.service.impl.BaseServiceImpl;
import com.vogue.supplymall.order.domain.service.OrderItemService;
import com.vogue.supplymall.order.domain.service.OrderPullService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拉取订单对外接口
 *
 * @author 崔岳
 */
@RestController
public class OrderPullController extends BaseController {

	/**
	 * The constant LOGGER_ORDERPULLCONTROLLER.
	 */
	public static final Logger LOGGER_ORDERPULLCONTROLLER = LoggerFactory.getLogger(OrderPullController.class);

	/** 各个用户（企业）拉取单据的时间记录，目前要求间隔 30 秒 */
	private static Map<String, Long> pullDateList = new HashMap<>();

	/** 各个用户（企业）拉取单据的时间记录，目前要求间隔 30 秒 */
	@Value("${pullorder.interval.second}")
	private Long pullorderIntervalSecond = 30L;
	@Autowired
	private ColValidateService colValidateService;
	@Resource
	private OrderPullService orderPullService;
	@Resource
	private BaseCodeService baseCodeService;
	@Autowired
	private MessageSourceUtils msu;
	@Resource
	private OrderItemService orderItemService;

	/**
	 * 拉取订单初始化接口（外销订单和采购订单）
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the string
	 */
	@RequestMapping(value = "/ns/{appver}/match/initPullSellData", method = RequestMethod.POST)
	public String tempIner(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) OrderPullCountDTO baseDTO) {
		Map<String, Object> resultMap = new HashMap<>();
		long timestamp = System.currentTimeMillis();

		// 停顿2秒
		while (true) {
			if (System.currentTimeMillis() - timestamp > 2000L) {
				break;
			}
		}

		Date maxdate = new Date(timestamp);
		Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
		Map<String, Object> map = new HashMap<>();
		switch (baseDTO.getPullType()) {
			case 0 : map = orderPullService.pullSellCount(syscodeid, maxdate); break;
			case 1 : map = orderPullService.pullBuyCount(syscodeid, maxdate); break;
			default : break;
		}
		map.put("resultFlag", true);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("endDate", sdf.format(maxdate));
		// resultMap.put("resultFlag", true);
		// resultMap.put("endDate", "2018-7-13 14:01:59:59.997");
		// resultMap.put("totalCnt", 600);

		String json = new Gson().toJson(map);
		return json;

	}

//	/**
//	 * 拉取卖家订单
//	 */
//	@RequestMapping(value = "/ns/{appver}/match/pullsell", method = RequestMethod.POST)
//	public ControllerResultInfo pullSellOrderController(HttpServletRequest request, HttpServletResponse response,
//			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
//			@RequestBody(required = true) OrderPullDTO baseDTO) {
//
//		ControllerResultInfo result = new ControllerResultInfo();
//		boolean resultFlag = true;
//		Integer pullCnt = baseDTO.getPullCnt() != null ? baseDTO.getPullCnt() : 10000;
//		List<Map<String, Object>> errList = new ArrayList<>();
//		long timestamp = System.currentTimeMillis();
//		if(baseDTO.getMaxdate() != null) {
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			try {
//				timestamp = sdf.parse(baseDTO.getMaxdate()).getTime();
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//		StringBuffer errmsg = new StringBuffer();
//		String pName = request.getHeader("pname");
//
//		// 首先验证系统注册码与开通手机以及机构id是否一致
//		try {
//			errList = colValidateService.safetyValidate(baseDTO, false, "orderBill");
//		} catch (Exception e) {
//			resultFlag = false;
//		}
//
//		if (errList.size() > 0) {
//			resultFlag = false;
//			for (Map<String, Object> map : errList) {
//				errmsg.append(map.get(BaseServiceImpl.errInfo)).append(";");
//			}
//		} else {
//			// 验证距上次拉取是否已经间隔30秒
////			if (!isCanPull(baseDTO.getRegistercode(), timestamp, pName)) {
////				errmsg.append(msu.getMessage("match.pullorder.tooOften",
////						new String[] { getPromptTimeMsg(pullorderIntervalSecond.longValue()) }));
////				resultFlag = false;
////			} else {
////				// 停顿2秒
////				while (true) {
////					if (System.currentTimeMillis() - timestamp > 2000L) {
////						break;
////					}
////				}
////			}
//			if (resultFlag) {
//				Date maxdate = new Date(timestamp);
//
//				Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
//				List<Map<String, Object>> list = orderPullService.pullSell(syscodeid, maxdate);
//				Map<String, OrderPullResultDTO> ordermap = new HashMap<>();
//				OrderPullResultDTO dto = null;
//				OrderDetailPullResultDTO detaildto = null;
//				List<OrderDetailPullResultDTO> detaillist = null;
//				int index = 0;
//				for (Map<String, Object> map : list) {
//					if (ordermap.containsKey(map.get("ordernumber"))) {
//						Gson gson = new Gson();
//						dto = gson.fromJson(gson.toJson(ordermap.get(map.get("ordernumber"))),
//								OrderPullResultDTO.class);
//					} else {
//						if(pullCnt == index++) {
//							break;
//						}
//						dto = new OrderPullResultDTO();
//						Long tendId = (Long) map.get("tendid");
//						dto.setTendid(tendId.intValue());
//						dto.setOrdernumber(map.get("ordernumber"));
//						dto.setCreatedate(map.get("createdate"));
//						dto.setBuyentname(map.get("buyentname"));
//						dto.setBuyshopname(map.get("buyshopname"));
//						dto.setBuyentid(map.get("buyentid"));
//						dto.setBuyshopid(map.get("buyshopid"));
//						dto.setBuyaddress(map.get("buyaddress"));
//						dto.setBuyname(map.get("buyname"));
//						dto.setBuytel(map.get("buytel"));
//						dto.setSyscode(map.get("syscode"));
//						dto.setMemo(map.get("memo"));
//						dto.setFreight(map.get("freight"));
//						dto.setFinalprice(map.get("finalprice"));
//						dto.setSellshopid(map.get("sellshopid"));
//						dto.setSellshopname("1");
//						dto.setSellentid("1");
//						dto.setSellentname("1");
//						dto.setTotalprice(map.get("totalprice"));
//						detaillist = new ArrayList<>();
//						dto.setDetail(detaillist);
//					}
//					detaillist = (List<OrderDetailPullResultDTO>) dto.getDetail();
//					detaildto = new OrderDetailPullResultDTO();
//					detaildto.setProductname(map.get("productname"));
//					detaildto.setProductunit(map.get("productunit"));
//					detaildto.setProductquantity(map.get("productquantity"));
//					detaildto.setProductprice(map.get("productprice"));
//					detaildto.setDiscountprice(map.get("discountprice"));
//					detaildto.setItemid(map.get("itemid"));
//					detaildto.setUnitid(map.get("unitid"));
//					detaildto.setBuystoreid(map.get("buystoreid"));
//					detaildto.setBuystorename(map.get("buystorename"));
//					detaildto.setSendCount(map.get("sendCount"));
//					detaildto.setSendMoney(map.get("sendMoney"));
//					detaildto.setDiffCount(map.get("diffCount"));
//					detaildto.setDiffMoney(map.get("diffMoney"));
//					detaillist.add(detaildto);
//					ordermap.put((String) map.get("ordernumber"), dto);
//				}
//				result.setData(ordermap.values());
//			}
//		}
//		result.setResult(resultFlag);
//		result.setMsg(errmsg.toString());
//		return result;
//	}

	/**
	 * 拉取买家订单
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the controller result info
	 */
	@RequestMapping(value = "/ns/{appver}/match/pullbuy", method = RequestMethod.POST)
	public ControllerResultInfo pullBuyOrderController(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) OrderPullDTO baseDTO) {

		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		String orderIds = "";
		Map<String, Object> resultMap = new HashMap<>();
		List<Map<String, Object>> pmList = new ArrayList<>();
		Integer pullCnt = baseDTO.getPullCnt() != null ? baseDTO.getPullCnt() : 10000;
		List<Map<String, Object>> errList = new ArrayList<>();
		long timestamp = System.currentTimeMillis();
		if (baseDTO.getMaxdate() != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				timestamp = sdf.parse(baseDTO.getMaxdate()).getTime();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		StringBuffer errmsg = new StringBuffer();
		String pName = request.getHeader("pname");

		// 首先验证系统注册码与开通手机以及机构id是否一致
		try {
			errList = colValidateService.safetyValidate(baseDTO, false, "orderBill");
		} catch (Exception e) {
			resultFlag = false;
		}

		if (errList.size() > 0) {
			resultFlag = false;
			for (Map<String, Object> map : errList) {
				errmsg.append(map.get(BaseServiceImpl.errInfo)).append(";");
			}
		} else {
			// 验证距上次拉取是否已经间隔30秒
//			if (!isCanPull(baseDTO.getRegistercode(), timestamp, pName)) {
//				errmsg.append(msu.getMessage("match.pullorder.tooOften",
//						new String[] { getPromptTimeMsg(pullorderIntervalSecond.longValue()) }));
//				resultFlag = false;
//			} else {
//				// 停顿2秒
//				while (true) {
//					if (System.currentTimeMillis() - timestamp > 2000L) {
//						break;
//					}
//				}
//			}
			if (resultFlag) {
				Date maxdate = new Date(timestamp);

				Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
				List<Map<String, Object>> list = null;
				switch (baseDTO.getPullType()) {
					case 0: list = orderPullService.pullSell(syscodeid, maxdate); break;
					case 1: list = orderPullService.pullBuy(syscodeid, maxdate); break;
					default:break;
				}
				Map<String, OrderPullResultDTO> ordermap = new HashMap<>();
				Map<String, String> detailMap=new HashMap<>();
				OrderPullResultDTO dto = null;
				OrderPayVoucherDTO opvDTO=null;
				OrderDetailPullResultDTO detaildto = null;
				List<OrderPayVoucherDTO> opbList=null;
				List<OrderDetailPullResultDTO> detaillist = null;
				int index = 0;
				boolean loopFlag=false;  //用于判断支付凭证是否还需要循环
				
				for (Map<String, Object> map : list) {
					if (ordermap.containsKey(map.get("ordernumber"))) {
						Gson gson = new Gson();
						dto = gson.fromJson(gson.toJson(ordermap.get(map.get("ordernumber"))),
								OrderPullResultDTO.class);
					} else {
						
						loopFlag=true;  //新的订单，需要获取支付凭证
						
						if (pullCnt == index++) {
							break;
						}
						dto = new OrderPullResultDTO();
						Long tendId = (Long) map.get("tendid");
						dto.setTendid(tendId.intValue());
						dto.setOrdernumber(map.get("ordernumber"));
						dto.setCreatedate(map.get("createdate"));
						dto.setBuyentname(map.get("buyentname"));
						dto.setBuyshopname(map.get("buyshopname"));
						dto.setBuyentid(map.get("buyentid"));
						dto.setOrganid(map.get("organid"));
						dto.setBuyshopid(map.get("buyshopid"));
						dto.setBuyaddress(map.get("buyaddress"));
						dto.setBuyname(map.get("buyname"));
						dto.setBuytel(map.get("buytel"));
						dto.setSyscode(map.get("syscode"));
						dto.setMemo(map.get("memo"));
						dto.setFreight(map.get("freight"));
						dto.setFinalprice(map.get("finalprice"));
						dto.setSellshopid(map.get("sellshopid"));
						dto.setSellshopname(map.get("sellshopname"));
						dto.setSellentid(map.get("sellentid"));
						dto.setSellentname(map.get("sellentname"));
						dto.setTotalprice(map.get("totalprice"));
						detaillist = new ArrayList<>();
						dto.setDetail(detaillist);
						opbList=new ArrayList<>();
						dto.setOpvList(opbList);
					}
					
					if((((ordermap.isEmpty()||ordermap.containsKey(map.get("ordernumber")))&&
						(detailMap.isEmpty()||detailMap.get("itemId").equals(map.get("itemid").toString())))||
						!ordermap.containsKey(map.get("ordernumber")))&&
						loopFlag) {		//如果是同一张订单同一个品项或者不同的订单且循环标记为true，则支付凭证需要保存
						
						opbList=dto.getOpvList();
						
						if(StringUtils.isNotBlank(map.get("paymentid").toString())) {
							opvDTO=new OrderPayVoucherDTO();
							opvDTO.setPaymentid(map.get("paymentid"));
							opvDTO.setPayurl(map.get("payurl"));
							
							opbList.add(opvDTO);
						}
						
					}
					
					if((ordermap.containsKey(map.get("ordernumber")))&&
					(!detailMap.isEmpty()&&detailMap.get("itemId").equals(map.get("itemid").toString()))) {			//如果是同一张订单，同样的品项，则不需要再次保存明细信息
						ordermap.put((String) map.get("ordernumber"), dto);
						
						continue;
					}else {	
						
						if(ordermap.containsKey(map.get("ordernumber"))&&!detailMap.isEmpty()&&!detailMap.get("itemId").equals(map.get("itemid").toString())) {
							loopFlag=false;
						}
						
						//得到订单id
						orderIds += map.get("id").toString() + ",";
						detaillist = (List<OrderDetailPullResultDTO>) dto.getDetail();
						detaildto = new OrderDetailPullResultDTO();
						detaildto.setProductname(map.get("productname"));
						detaildto.setProductunit(map.get("productunit"));
						detaildto.setProductquantity(map.get("productquantity"));
						detaildto.setProductprice(map.get("productprice"));
						detaildto.setDiscountprice(map.get("discountprice"));
						detaildto.setItemid(map.get("itemid"));
						detaildto.setUnitid(map.get("unitid"));
						detaildto.setBuystoreid(map.get("buystoreid"));
						detaildto.setBuystorename(map.get("buystorename"));
						detaildto.setSupplyid(map.get("supplyid").toString());
						detaildto.setSendCount(map.get("sendcount"));
						detaildto.setSendMoney(map.get("sendmoney"));
						detaildto.setDiffCount(map.get("diffcount"));
						detaildto.setDiffMoney(map.get("diffmoney"));
						detaillist.add(detaildto);
						ordermap.put((String) map.get("ordernumber"), dto);
						
						detailMap.put("itemId", map.get("itemid").toString());
					}
					
				}
				//result.setData(ordermap.values());
				resultMap.put("orderInfo", ordermap.values());
			}
		}
		
		//根据订单id得到订单的相关支付方式
		if (StringUtils.isNotBlank(orderIds)) {
			orderIds = orderIds.substring(0, orderIds.length() - 1);
			pmList = orderPullService.getPayModeByOrderId(orderIds);
		}
		resultMap.put("payInfo", pmList);
		result.setData(resultMap);
		result.setResult(resultFlag);
		result.setMsg(errmsg.toString());
		return result;
	}

	/**
	 * 推送订单状态
	 *
	 * @param request  request
	 * @param response response
	 * @param appver   appver
	 * @param baseDTO  baseDTO
	 * @return string
	 */
	@RequestMapping(value = "/ns/{appver}/match/reducepullstate", method = RequestMethod.POST)
	public String reducePullStateController(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) BaseDTO<List<OrderPushDTO>> baseDTO) {

		Map<String, Object> resultMap = new HashMap<>();
		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		List<Map<String, Object>> errList = new ArrayList<>();
		long timestamp = System.currentTimeMillis();
		StringBuffer errmsg = new StringBuffer();
		String pName = request.getHeader("pname");
		// 首先进行验证
		try {
			errList = colValidateService.orderPushValidate(baseDTO);
		} catch (Exception e) {
			resultFlag = false;
		}

		if (errList.size() > 0) {
			resultFlag = false;
			for (Map<String, Object> map : errList) {
				errmsg.append(map.get(BaseServiceImpl.errInfo)).append(";");
			}
		} else {
			// 验证距上次拉取是否已经间隔30秒
			if (!isCanPull(baseDTO.getRegistercode(), timestamp, pName)) {
				errmsg.append(msu.getMessage("match.pullorder.tooOften",
						new String[] {getPromptTimeMsg(pullorderIntervalSecond.longValue())}));
				resultFlag = false;
			}

			if (resultFlag) {
				// 要判断字符串格式是否正确，然后逐个更新，最终返回成功条数，失败条数和失败原因
				List<OrderPushDTO> opDTOs = baseDTO.getData();
				Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
				try {
					//先更新差异数量
					for (OrderPushDTO opDTO:opDTOs) {
						List<PushBillInfoDTO> pbiList = opDTO.getBillInfo();
						if (pbiList.size() > 0 && pbiList.get(0) != null) {
							orderItemService.changSendInfo(pbiList);
						}
					}
					resultMap = orderPullService.reducePullSellState(syscodeid, opDTOs);
					String json = new Gson().toJson(resultMap);
					System.out.println(json);
					return json;
				} catch (Exception e) {
					resultFlag = false;
					e.printStackTrace();
				}
			}
		}

		// 返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("successCnt", 0);
		resultMap.put("details", errList);
		String json = new Gson().toJson(resultMap);

		return json;
	}

	/**
	 * 更新拉取卖家订单状态（已拉取）
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the controller result info
	 */
	@RequestMapping(value = "/ns/{appver}/match/pullsellstate", method = RequestMethod.POST)
	public ControllerResultInfo pullSellStateController(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) OrderPullDTO baseDTO) {
		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		List<Map<String, Object>> errList = new ArrayList<>();
		// 首先验证系统注册码与开通手机以及机构id是否一致
		// try {
		// errList = colValidateService.safetyValidate(baseDTO, false);
		// } catch (Exception e) {
		// resultFlag = false;
		// }
		// 验证日期参数是否是合法日期格式
		if (!colValidateService.checkDateFormat(baseDTO.getMaxdate())) {
			errList = colValidateService.dateFormatErrorInfo(errList, null, null, msu.getMessage("pulldate", null));
		}

		if (errList.size() > 0) {
			result.setData(errList);
		} else {
			Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date;
			try {
				date = formatter.parse(baseDTO.getMaxdate());
				switch (baseDTO.getPullType()) {
				case 0 :
					orderPullService.updatePullSellState(syscodeid, date,
							baseDTO.getPullCnt() == null ? 10000 : baseDTO.getPullCnt());
					break;
				case 1 :
					orderPullService.updatePullBuyState(syscodeid, date,
							baseDTO.getPullCnt() == null ? 10000 : baseDTO.getPullCnt());
					break;
				default : break;
			}
			} catch (ParseException e) {
				resultFlag = false;
				LOGGER_ORDERPULLCONTROLLER.error("设置订单的拉取状态，时间戳字段日期格式不合法" + baseDTO.getMaxdate());
			}
		}
		result.setResult(resultFlag);
		return result;
	}

	/**
	 * 更新拉取买家订单状态（已拉取）
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the controller result info
	 */
	@RequestMapping(value = "/ns/{appver}/match/pullbuystate", method = RequestMethod.POST)
	public ControllerResultInfo pullBuyStateController(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) OrderPullDTO baseDTO) {
		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		List<Map<String, Object>> errList = new ArrayList<>();
		// 首先验证系统注册码与开通手机以及机构id是否一致
		// try {
		// errList = colValidateService.safetyValidate(baseDTO, false);
		// } catch (Exception e) {
		// resultFlag = false;
		// }
		// 验证日期参数是否是合法日期格式
		if (!colValidateService.checkDateFormat(baseDTO.getMaxdate())) {
			errList = colValidateService.dateFormatErrorInfo(errList, null, null, msu.getMessage("pulldate", null));
		}

		if (errList.size() > 0) {
			result.setData(errList);
		} else {
			Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date;
			try {
				date = formatter.parse(baseDTO.getMaxdate());
				switch (baseDTO.getPullType()) {
					case 0 : orderPullService.updatePullSellState(syscodeid, date,
							baseDTO.getPullCnt() == null ? 10000 : baseDTO.getPullCnt());
					break;
					case 1 : orderPullService.updatePullBuyState(syscodeid, date,
							baseDTO.getPullCnt() == null ? 10000 : baseDTO.getPullCnt());
					break;
					default : break;
				}
			} catch (ParseException e) {
				resultFlag = false;
				LOGGER_ORDERPULLCONTROLLER.error("设置订单的拉取状态，时间戳字段日期格式不合法" + baseDTO.getMaxdate());
			}
		}
		result.setResult(resultFlag);
		return result;
	}


	/**
	 * 拉取订单初始化接口（外销退货单）
	 * 检查是否有可拉取的订单数据
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the string
	 */
	@RequestMapping(value = "/ns/{appver}/match/initPullRefundData", method = RequestMethod.POST)
	public String initPullRefundDataController(HttpServletRequest request, HttpServletResponse response,
						   @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
						   @RequestBody(required = true) OrderPullCountDTO baseDTO) {
		Map<String, Object> resultMap = new HashMap<>();
		long timestamp = System.currentTimeMillis();

		// 停顿2秒
		while (true) {
			if (System.currentTimeMillis() - timestamp > 2000L) {
				break;
			}
		}

		Date maxdate = new Date(timestamp);
		//检查注册号是否存在，存在即合法，否则不合法
		Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
		Map<String, Object> map = new HashMap<>();
		switch (baseDTO.getPullType()) {
			case 0 : map = orderPullService.pullRefundSellCount(syscodeid, maxdate); break;
			//case 1 : map = orderPullService.pullBuyCount(syscodeid, maxdate);break;
			default : break;
		}
		map.put("resultFlag", true);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("endDate", sdf.format(maxdate));
		String json = new Gson().toJson(map);
		return json;
	}

	/**
	 * 拉取外销退货单订单
	 *
	 * @param request  the request
	 * @param response the response
	 * @param appver   the appver
	 * @param baseDTO  the base dto
	 * @return the controller result info
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/ns/{appver}/match/pullRefund", method = RequestMethod.POST)
	public ControllerResultInfo pullRefundController(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) OrderPullDTO baseDTO) {

		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		String orderIds = "";
		Map<String, Object> resultMap = new HashMap<>();
		List<Map<String, Object>> pmList = new ArrayList<>();
		Integer pullCnt = baseDTO.getPullCnt() != null ? baseDTO.getPullCnt() : 10000;
		List<Map<String, Object>> errList = new ArrayList<>();
		long timestamp = System.currentTimeMillis();
		if (baseDTO.getMaxdate() != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				timestamp = sdf.parse(baseDTO.getMaxdate()).getTime();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		StringBuffer errmsg = new StringBuffer();

		// 首先验证系统注册码与开通手机以及机构id是否一致
		try {
			errList = colValidateService.safetyValidate(baseDTO, false, "orderBill");
		} catch (Exception e) {
			resultFlag = false;
		}

		if (errList.size() > 0) {
			resultFlag = false;
			for (Map<String, Object> map : errList) {
				errmsg.append(map.get(BaseServiceImpl.errInfo)).append(";");
			}
		} else {
			if (resultFlag) {
				Date maxdate = new Date(timestamp);

				Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
				List<Map<String, Object>> list = null;
				switch (baseDTO.getPullType()) {
					case 0: list = orderPullService.pullRefundSell(syscodeid, maxdate); break;
					//case 1: list = orderPullService.pullBuy(syscodeid, maxdate); break;
					default:break;
				}

				Map<String, RefundPullResultDTO> ordermap = new HashMap<>();
				RefundPullResultDTO dto = null;
				RefundDetailPullResultDTO detaildto = null;
				UploadDTO imgdto = null;
				List<RefundDetailPullResultDTO> detaillist = null;
				List<UploadDTO> imglist = null;

				int index=0;
				Map<String, RefundDetailPullResultDTO> detailMap=new HashMap<>();
				
				for (Map<String, Object> map : list) {
					if (ordermap.containsKey(map.get("id").toString())) {
						Gson gson = new Gson();
						dto = gson.fromJson(gson.toJson(ordermap.get(map.get("id").toString())),
								RefundPullResultDTO.class);
					} else {
						if (pullCnt == index++) {
							break;
						}
						dto = new RefundPullResultDTO();
						Long tendId = (Long) map.get("tendid");
						dto.setTendid(tendId.intValue());
						dto.setOrdernumber(map.get("ordernumber"));
						dto.setRefundnumber(map.get("refundnumber"));
						dto.setCreatedate(map.get("createdate"));
						dto.setBuyentname(map.get("buyentname"));
						dto.setBuyshopname(map.get("buyshopname"));
						dto.setBuyentid(map.get("buyentid"));
						dto.setOrganid(map.get("organid"));
						dto.setBuyshopid(map.get("buyshopid"));
						dto.setBuyaddress(map.get("buyaddress"));
						dto.setBuyname(map.get("buyname"));
						dto.setBuytel(map.get("buytel"));
						dto.setSyscode(map.get("syscode"));
						dto.setMemo(map.get("memo"));
						dto.setRefundreason(map.get("refundreason"));
						dto.setTotalprice(map.get("totalprice"));
						dto.setRefundtotalprice(map.get("refundtotalprice"));
						dto.setRefundfreight(map.get("refundfreight"));
						dto.setRefundfinalprice(map.get("refundfinalprice"));
						dto.setSellshopid(map.get("sellshopid"));
						dto.setSellshopname(map.get("sellshopname"));
						dto.setSellentid(map.get("sellentid"));
						dto.setSellentname(map.get("sellentname"));
						dto.setTotalprice(map.get("totalprice"));
						detaillist = new ArrayList<>();
						dto.setDetail(detaillist);
					}
					if(detailMap.containsKey(map.get("refunddetailid").toString())) {
//						Gson gson = new Gson();
//						int lenth=((List<RefundDetailPullResultDTO>) ordermap.get(map.get("id").toString()).getDetail()).size()-1;
//						detaildto = gson.fromJson(gson.toJson( ((List<RefundDetailPullResultDTO>) ordermap.get(map.get("id").toString()).getDetail()).get(lenth) ),							
//								RefundDetailPullResultDTO.class);
						detaildto=detaillist.get(detaillist.size()-1);
						
					}else {
						//得到订单id
						orderIds += map.get("id").toString() + ",";
						detaillist = (List<RefundDetailPullResultDTO>) dto.getDetail();
						detaildto = new RefundDetailPullResultDTO();
						detaildto.setProductname(map.get("productname"));
						detaildto.setProductunit(map.get("productunit"));
						detaildto.setProductquantity(map.get("productquantity"));
						detaildto.setRefundquantity(map.get("refundquantity"));
						detaildto.setProductprice(map.get("productprice"));
						detaildto.setDiscountprice(map.get("discountprice"));
						detaildto.setItemid(map.get("itemid"));
						detaildto.setUnitid(map.get("unitid"));
						detaildto.setBuystoreid(map.get("buystoreid"));
						detaildto.setBuystorename(map.get("buystorename"));
						detaildto.setSupplyid(map.get("supplyid"));
						detaildto.setRefunddetailid(map.get("refunddetailid"));
						detaildto.setRefundmoney(map.get("refundmoney"));
						imglist = new ArrayList<>();
						detaildto.setImginfo(imglist);
						detaillist.add(detaildto);
			
					}
					
					imglist =(List<UploadDTO>) detaildto.getImginfo();
					if (null != map.get("refundimgId")) {
//						Map map1 = new HashMap<>();
//						map1.put("id", map.get("refundimgId").toString());
//						map1.put("imgurl", map.get("url").toString());
						imgdto=new UploadDTO();
	                    imgdto.setId(map.get("refundimgId").toString());
						imgdto.setImgtype(Integer.parseInt(map.get("imgtype").toString()));
						imgdto.setImgurl(map.get("url").toString());
						imgdto.setOrderdetailid(map.get("refunddetailid").toString());
						imglist.add(imgdto);
					}
					dto.setDetail(detaillist);
					ordermap.put(map.get("id").toString(), dto);
					detailMap.put(map.get("refunddetailid").toString(), detaildto);
				}
				
//				for (Map<String, Object> map : list) {
//					if (ordermap.size() >= pullCnt) {
//						break;
//					}
//					if (null != map.get("refundimgId")) {
//						imgdto = new UploadDTO();
//                        imgdto.setId(map.get("refundimgId").toString());
//						imgdto.setImgtype(Integer.parseInt(map.get("imgtype").toString()));
//						imgdto.setImgurl(map.get("url").toString());
//						imgdto.setOrderdetailid(map.get("refunddetailid").toString());
//					}
//					if (imglist != null) {
//						boolean hasDetai = false;
//						for (UploadDTO img : imglist) {
//							if (map.get("refunddetailid").toString().equals(img.getOrderdetailid())) {
//								hasDetai = true;
//								break;
//							}
//						}
//						imglist.add(imgdto);
//						if (!hasDetai) {
//							detaildto = new RefundDetailPullResultDTO();
//							detaildto.setProductname(map.get("productname"));
//							detaildto.setProductunit(map.get("productunit"));
//							detaildto.setProductquantity(map.get("productquantity"));
//							detaildto.setRefundquantity(map.get("refundquantity"));
//							detaildto.setProductprice(map.get("productprice"));
//							detaildto.setDiscountprice(map.get("discountprice"));
//							detaildto.setItemid(map.get("itemid"));
//							detaildto.setUnitid(map.get("unitid"));
//							detaildto.setBuystoreid(map.get("buystoreid"));
//							detaildto.setBuystorename(map.get("buystorename"));
//							detaildto.setSupplyid(map.get("supplyid"));
//							detaildto.setRefunddetailid(map.get("refunddetailid"));
//							detaildto.setRefundmoney(map.get("refundmoney"));
//							detaildto.setImginfo(imglist);
//							if (detaillist != null) {
//								boolean hasOrder = false;
//								for (RefundDetailPullResultDTO detail : detaillist) {
//									if (map.get("supplyid").toString().equals(detail.getSupplyid())) {
//										hasOrder = true;
//									}
//								}
//								if (!hasOrder) {
//									dto = new RefundPullResultDTO();
//									Long tendId = (Long) map.get("tendid");
//									dto.setTendid(tendId.intValue());
//									dto.setOrdernumber(map.get("ordernumber"));
//									dto.setRefundnumber(map.get("refundnumber"));
//									dto.setCreatedate(map.get("createdate"));
//									dto.setBuyentname(map.get("buyentname"));
//									dto.setBuyshopname(map.get("buyshopname"));
//									dto.setBuyentid(map.get("buyentid"));
//									dto.setOrganid(map.get("organid"));
//									dto.setBuyshopid(map.get("buyshopid"));
//									dto.setBuyaddress(map.get("buyaddress"));
//									dto.setBuyname(map.get("buyname"));
//									dto.setBuytel(map.get("buytel"));
//									dto.setSyscode(map.get("syscode"));
//									dto.setMemo(map.get("memo"));
//                                   dto.setRefundreason(map.get("refundreason"));
//									dto.setTotalprice(map.get("totalprice"));
//									dto.setRefundtotalprice(map.get("refundtotalprice"));
//									dto.setRefundfreight(map.get("refundfreight"));
//									dto.setRefundfinalprice(map.get("refundfinalprice"));
//									dto.setSellshopid(map.get("sellshopid"));
//									dto.setSellshopname(map.get("sellshopname"));
//									dto.setSellentid(map.get("sellentid"));
//									dto.setSellentname(map.get("sellentname"));
//									dto.setTotalprice(map.get("totalprice"));
//								}
//								detaillist.add(detaildto);
//							} else {
//								detaillist = new ArrayList<>();
//								detaillist.add(detaildto);
//							}
//						}
//
//					} else {
//                        if (imgdto != null) {
//                            imglist = new ArrayList<>();
//                            imglist.add(imgdto);
//                        }
//						detaillist = new ArrayList<>();
//						detaildto = new RefundDetailPullResultDTO();
//						detaildto.setProductname(map.get("productname"));
//						detaildto.setProductunit(map.get("productunit"));
//						detaildto.setProductquantity(map.get("productquantity"));
//						detaildto.setRefundquantity(map.get("refundquantity"));
//						detaildto.setProductprice(map.get("productprice"));
//						detaildto.setDiscountprice(map.get("discountprice"));
//						detaildto.setItemid(map.get("itemid"));
//						detaildto.setUnitid(map.get("unitid"));
//						detaildto.setBuystoreid(map.get("buystoreid"));
//						detaildto.setBuystorename(map.get("buystorename"));
//						detaildto.setSupplyid(map.get("supplyid"));
//						detaildto.setRefunddetailid(map.get("refunddetailid"));
//						detaildto.setRefundmoney(map.get("refundmoney"));
//						detaildto.setImginfo(imglist);
//						detaillist.add(detaildto);
//
//						dto = new RefundPullResultDTO();
//						Long tendId = (Long) map.get("tendid");
//						dto.setTendid(tendId.intValue());
//						dto.setOrdernumber(map.get("ordernumber"));
//						dto.setRefundnumber(map.get("refundnumber"));
//						dto.setCreatedate(map.get("createdate"));
//						dto.setBuyentname(map.get("buyentname"));
//						dto.setBuyshopname(map.get("buyshopname"));
//						dto.setBuyentid(map.get("buyentid"));
//						dto.setOrganid(map.get("organid"));
//						dto.setBuyshopid(map.get("buyshopid"));
//						dto.setBuyaddress(map.get("buyaddress"));
//						dto.setBuyname(map.get("buyname"));
//						dto.setBuytel(map.get("buytel"));
//						dto.setSyscode(map.get("syscode"));
//						dto.setMemo(map.get("memo"));
//						dto.setRefundreason(map.get("refundreason"));
//						dto.setTotalprice(map.get("totalprice"));
//						dto.setRefundtotalprice(map.get("refundtotalprice"));
//						dto.setRefundfreight(map.get("refundfreight"));
//						dto.setRefundfinalprice(map.get("refundfinalprice"));
//						dto.setSellshopid(map.get("sellshopid"));
//						dto.setSellshopname(map.get("sellshopname"));
//						dto.setSellentid(map.get("sellentid"));
//						dto.setSellentname(map.get("sellentname"));
//						dto.setTotalprice(map.get("totalprice"));
//						dto.setDetail(detaillist);
//					}
//					ordermap.put((String) map.get("refundnumber"), dto);
//				}
				resultMap.put("orderInfo", ordermap.values());
			}
		}

		//根据退货订单id得到订单的相关支付方式
		if (StringUtils.isNotBlank(orderIds)) {
			orderIds = orderIds.substring(0, orderIds.length() - 1);
			pmList = orderPullService.getPayModeByOrderId(orderIds);
		}
		resultMap.put("payInfo", pmList);

		result.setData(resultMap);
		result.setResult(resultFlag);
		result.setMsg(errmsg.toString());
		return result;
	}

	/**
	 * 推送退货订单状态
	 *
	 * @param request  request
	 * @param response response
	 * @param appver   appver
	 * @param baseDTO  baseDTO
	 * @return String string
	 */
	@RequestMapping(value = "/ns/{appver}/match/reducePullRefundState", method = RequestMethod.POST)
	public String reducePullRefundStateController(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
			@RequestBody(required = true) BaseDTO<List<OrderPushDTO>> baseDTO) {

		Map<String, Object> resultMap = new HashMap<>();
		boolean resultFlag = true;
		List<Map<String, Object>> errList = new ArrayList<>();
		long timestamp = System.currentTimeMillis();
		StringBuffer errmsg = new StringBuffer();
		String pName = request.getHeader("pname");
		// 首先进行验证
		try {
			errList = colValidateService.orderPushValidate(baseDTO);
		} catch (Exception e) {
			resultFlag = false;
		}

		if (errList.size() > 0) {
			resultFlag = false;
			for (Map<String, Object> map : errList) {
				errmsg.append(map.get(BaseServiceImpl.errInfo)).append(";");
			}
		} else {
			// 验证距上次拉取是否已经间隔30秒
			if (!isCanPull(baseDTO.getRegistercode(), timestamp, pName)) {
				errmsg.append(msu.getMessage("match.pullorder.tooOften",
						new String[] {getPromptTimeMsg(pullorderIntervalSecond.longValue())}));
				resultFlag = false;
			}

			if (resultFlag) {
				// 要判断字符串格式是否正确，然后逐个更新，最终返回成功条数，失败条数和失败原因
				List<OrderPushDTO> opDTOs = baseDTO.getData();
				Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
				try {
					resultMap = orderPullService.reducePullSellRefundState(syscodeid, opDTOs);
					String json = new Gson().toJson(resultMap);
					System.out.println(json);
					return json;
				} catch (Exception e) {
					resultFlag = false;
					e.printStackTrace();
				}
			}
		}

		// 返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("successCnt", 0);
		resultMap.put("details", errList);
		String json = new Gson().toJson(resultMap);

		return json;
	}

	/**
	 * 中间件拉取后，回执更新卖家退货单状态（已拉取）
	 * 卖家将拉取商城的退货单数据设置成已拉取状态
	 *
	 * @param request  request
	 * @param response response
	 * @param appver   appver
	 * @param baseDTO  baseDTO
	 * @return ControllerResultInfo controller result info
	 */
	@RequestMapping(value = "/ns/{appver}/match/pullRefundSellState", method = RequestMethod.POST)
	public ControllerResultInfo pullRefundSellStateController(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            @RequestBody(required = true) OrderPullDTO baseDTO) {
		ControllerResultInfo result = new ControllerResultInfo();
		boolean resultFlag = true;
		List<Map<String, Object>> errList = new ArrayList<>();
		// 验证日期参数是否是合法日期格式
		if (!colValidateService.checkDateFormat(baseDTO.getMaxdate())) {
			errList = colValidateService.dateFormatErrorInfo(errList, null, null, msu.getMessage("pulldate", null));
		}

		if (errList.size() > 0) {
			result.setData(errList);
		} else {
			Long syscodeid = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date;
			try {
				date = formatter.parse(baseDTO.getMaxdate());
				switch (baseDTO.getPullType()) {
					case 0 : orderPullService.updatePullRefundSellState(syscodeid, date,
							baseDTO.getPullCnt() == null ? 10000 : baseDTO.getPullCnt());
					break;
					//case 1 : orderPullService.updatePullBuyState(syscodeid, date,
					// baseDTO.getPullCnt()==null?10000:baseDTO.getPullCnt()); break;
					default : break;
				}

			} catch (ParseException e) {
				resultFlag = false;
				LOGGER_ORDERPULLCONTROLLER.error("设置退货订单的拉取状态，时间戳字段日期格式不合法" + baseDTO.getMaxdate());
			}
		}
		result.setResult(resultFlag);
		return result;
	}

	/**
	 * 查看当前指定的企业是否可以进行拉取，如果距上次拉取时间没有超过30秒，则提示稍候再试
	 *
	 * @param sysdateid 企业开通商城编码id
	 * @param newdate   拉取时间
	 * @param pName     pName
	 * @return boolean
	 */
	public synchronized boolean isCanPull(Long sysdateid, Long newdate, String pName) {
		String key = sysdateid + pName;
		Long date = pullDateList.get(key);
		boolean flag = true;
		if (date == null) {
			pullDateList.put(key, newdate);
		} else {
			if (newdate.longValue() - date.longValue() > pullorderIntervalSecond.longValue() * 1000) {
				pullDateList.put(key, newdate);
			} else {
				flag = false;
			}
		}
		return flag;
	}

	/**
	 * 根据秒数获取x分x秒的提示文字格式（目前只支持到秒）
	 *
	 * @param second 秒数
	 * @return prompt time msg
	 */
	public String getPromptTimeMsg(long second) {
		StringBuffer msg = new StringBuffer();
		msg.append((second / 60 == 0 ? "" : (second / 60) + msu.getMessage("global.system.minute", null)))
				.append((second % 60) + msu.getMessage("global.system.second", null));
		return msg.toString();
	}



}
